#include "connection.h"

#include <QtGlobal>
#include <QDebug>

#include <unistd.h>

Connection::Connection(quint32 uid, int fd[], QObject *parent)
    : QObject{parent}
{
    m_localSocket = new QLocalSocket(this);
    m_localSocket->setSocketDescriptor(fd[0]);

    connect(m_localSocket, &QLocalSocket::readyRead, this, &Connection::onSocketReadyRead);

    m_localSocket->write("test");

    QString dbusAddress = QString("unix:path=/run/user/%1/bus").arg(uid);
    auto sysenvs = QProcessEnvironment::systemEnvironment();
    sysenvs.insert("DBUS_SESSION_BUS_ADDRESS", dbusAddress);
    m_child = new QProcess;
    m_child->setProcessEnvironment(sysenvs);
    //m_child->setProcessChannelMode(QProcess::SeparateChannels);
    m_child->setProcessChannelMode(QProcess::ForwardedChannels);
    m_child->setProgram("/home/kylin/git/build-index-framework-unknown-Debug/service/ukui-index-framework-service");
    m_child->setArguments(QStringList() << QString::number(uid) << QString::number(fd[0]) << QString::number(fd[1]));
    m_child->start();

    qDebug() << m_child->arguments();
    connect(m_child, &QProcess::started, this, [=]{close(fd[1]);});
    connect(m_child, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this, &Connection::onChildFinished);
}

Connection::~Connection()
{
    m_child->disconnect();
    m_child->close();
    m_child->waitForFinished();
    delete m_child;
}

void Connection::writeMessage(QString msg)
{
    m_localSocket->write(msg.toLocal8Bit());
}

void Connection::writeBuffer(const QByteArray &buffer)
{
    m_localSocket->write(buffer);
    m_localSocket->write("\0");
    m_localSocket->flush();
}

void Connection::onSocketReadyRead()
{
    auto data = m_localSocket->readAll();
    qDebug() << "[HOST] Received raw data:" << data; // 添加调试输出
    auto msgs = data.split('\0');
    for (auto msg : msgs) {
        qDebug() << "host receive client msg call" << msg;
        emit messageReceived(msg);
    }
}

void Connection::onChildFinished(int exitCode, QProcess::ExitStatus status)
{
    qDebug() << "child finished with code" << exitCode;
    if (status == QProcess::NormalExit) {
        emit disconnected();
    } else {
        qWarning() << "child exit unexpectedly, try restart";
        m_child->start();
    }
}
